package activitis;

import utils.BaseAsync;
import utils.Constantes;
import utils.PreferencesHelper;

import com.example.baserapitaxi.BaseLoginActivity;
import com.google.gson.Gson;

import controladores.ControladorChoferes;
import controladores.ControladorPasajeros;
import controladores.ControladorViajes;
import entidades.Movil;
import entidades.Viaje;
import entidades.usuarios.Pasajero;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class LoginChoferActivity extends BaseLoginActivity
{	
	private Pasajero pasajero;
	
	@Override
	protected void login(String email, String clave)
	{
		if (check)
			new CheckDatos(email, clave).execute();
		else
			new IniciarSesion(email, clave).execute();
	}

	@Override
	public void registrar(View view)
	{
		Intent intent = new Intent (LoginChoferActivity.this, RegistroChoferActivity.class);
		startActivity(intent);
		
//		getDialogoRegistro().show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == RegistroMovilActivity.REGISTRO_MOVIL && resultCode == Activity.RESULT_OK)
		{
			String stringMovil = data.getStringExtra(Constantes.RegistroUsuario.MOVIL);
			
			if (stringMovil == null)
				return;
			
			Movil movil = new Gson().fromJson(stringMovil, Movil.class);
			
			new RegistrarChofer(movil).execute();
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Dialog getDialogoRegistro()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Registro");
		builder.setItems(new String[]
		{ "Soy pasajero.", "No tengo usuario." },
				new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						Intent intent;
						
						if (which == 0)
						{
							// Tiene usuario pasajero.
							intent = new Intent (LoginChoferActivity.this, LoginChoferActivity.class);
							intent.putExtra(BaseLoginActivity.booleanCheck, true);
						}
						else
						{
							// No tiene usuario;
							intent = new Intent (LoginChoferActivity.this, RegistroChoferActivity.class);
						}
						
						startActivity(intent);
					}
				});
		return builder.create();

	}

	private class IniciarSesion extends BaseAsync
	{
		private String email, clave;
		private long id;
		
		public IniciarSesion (String email, String clave)
		{
			super (LoginChoferActivity.this, "Iniciando...");
			
			this.email = email;
			this.clave = clave;
		}
		
		@Override
		protected Void doInBackground(Void... arg0)
		{
			id = new ControladorChoferes().iniciarSesion(email, clave, new PreferencesHelper(getApplicationContext()).getSharedPreferences().getString(PreferencesHelper.GCM, ""));
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			if (id > 0)
			{
				PreferencesHelper helper = new PreferencesHelper(getApplicationContext());
				
				helper.editKey(PreferencesHelper.ID, id);
				
				new BuscarViaje().execute();
			}
			else
				Toast.makeText(LoginChoferActivity.this, "Datos incorrectos.", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class BuscarViaje extends BaseAsync
	{
		private Class<?> iniciar;
		
		public BuscarViaje ()
		{
			super (LoginChoferActivity.this, "Cargando...");
		}
		
		@Override
		protected Void doInBackground(Void... arg0)
		{
			long id = new PreferencesHelper(getApplicationContext()).leerID();
			
			Viaje viaje = new ControladorViajes().getViajeChofer(id);
            
            if (viaje == null)
                // Si NO esta en viaje, voy a la pantalla de turno.
                iniciar = TurnoActivity.class;
            else
                // Si SI esta en viaje, levanto la pantalla de viaje.
                iniciar = InfoViajeActivity.class;

			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			if (iniciar != null)
            {
                Intent intent = new Intent(LoginChoferActivity.this, iniciar);
                super.onPostExecute(result);
                startActivity(intent);
            }
           
            finish();

		}
	}
	
	private class CheckDatos extends BaseAsync
	{
		private String email;
		private String clave;
		
		public CheckDatos (String email, String clave)
		{
			super (LoginChoferActivity.this, "Verificando...");
			
			this.email = email;
			this.clave = clave;
		}
		
		@Override
		protected Void doInBackground(Void... arg0)
		{
			pasajero = new ControladorPasajeros().checkDatos(email, clave);
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			if (pasajero != null)
			{
				Intent intent = new Intent (LoginChoferActivity.this, RegistroMovilActivity.class);
				startActivityForResult(intent, RegistroMovilActivity.REGISTRO_MOVIL);
				
//				Intent intent = new Intent (LoginChoferActivity.this, RegistroChoferActivity.class);
//				intent.putExtra(Constantes.DataBundle.PASAJERO, new Gson().toJson(res));
//				startActivity(intent);
//				finish();
			}
			else
				Toast.makeText(LoginChoferActivity.this, "Datos incorrectos.", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class RegistrarChofer extends BaseAsync
	{
		private Movil movil;
		private int res;
		
		public RegistrarChofer (Movil movil)
		{
			super (LoginChoferActivity.this, "Registrando...");
			
			this.movil = movil;
		}
		
		@Override
		protected Void doInBackground(Void... arg0)
		{
			res = new ControladorChoferes().registrarChofer(pasajero.getId(), movil);
			Log.i("LOG", "Registro chofer: " + res);
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			String mensaje = "";
			boolean volver = true;;
			
			switch (res)
			{
			case Constantes.Registro.NULL:
				mensaje = "Datos incorrectos!";
				volver = false;
				break;
			case Constantes.Registro.EMAIL_EXISTENTE:
				mensaje = "Ya existe ese Email! D:<";
				volver = true;
				break;
			case Constantes.Registro.OK:
				mensaje = "Registrado :D";
				volver = true;
				break;
			}
			
			alert(mensaje, volver);
		}
		
		private void alert (String mensaje, final boolean volver)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(LoginChoferActivity.this);
			builder.setMessage(mensaje)
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) 
			           {
			                if (volver)
			                	finish();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
}
